import asyncio
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo import MongoClient

# 全局复用连接（单例）
_sync_client = None
_async_client = None


def is_async_context() -> bool:
    """判断当前是否处于异步上下文"""
    try:
        asyncio.get_running_loop()
        return True
    except RuntimeError:
        return False


def linkMongo(collection_name: str,
              db_name: str = 'python',
              mongo_url: str = 'mongodb://127.0.0.1:27017/?directConnection=true'  # 默认本地
              ):
    """
    智能版 MongoDB 连接函数：
    - 同步环境：返回 pymongo.collection.Collection
    - 异步环境：返回 motor.AsyncIOMotorCollection（需 await）
    """
    if is_async_context():
        return _linkMongo_async(collection_name, db_name, mongo_url)
    else:
        return _linkMongo_sync(collection_name, db_name, mongo_url)


def _linkMongo_sync(collection_name, db_name, mongo_url):
    """同步连接 MongoDB"""
    global _sync_client
    if _sync_client is None:
        _sync_client = MongoClient(mongo_url, maxPoolSize=10, minPoolSize=1)
    try:
        db = _sync_client[db_name]
        return db[collection_name]
    except Exception as e:
        raise ConnectionError(f"[MongoDB Sync] Connection error: {e}")


async def _linkMongo_async(collection_name, db_name, mongo_url):
    """异步连接 MongoDB"""
    global _async_client
    if _async_client is None:
        _async_client = AsyncIOMotorClient(
            mongo_url, maxPoolSize=10, minPoolSize=1)
    try:
        db = _async_client[db_name]
        return db[collection_name]
    except Exception as e:
        raise ConnectionError(f"[MongoDB Async] Connection error: {e}")
